import { createStore } from "vuex";

import createPersistedState from "vuex-persistedstate";

export default createStore({
  state: {
    axiosLoading: false,
    newsDetails: [], //缓存新闻详情
    newsList: [], //缓存首页list
    userData: {
      titleImg: "",
      userCode: "",
      userName: "",
    },
    detailBackType: "",
    collectBackType: "",
    footerBar: [
      {
        key: "1",
        route: "/Home",
        text: "home",
        icon: "wap-home-o",
      },
      {
        key: "2",
        route: "/collect",
        text: "collect",
        icon: "star-o",
      },
      {
        key: "3",
        route: "/user",
        text: "user",
        icon: "manager-o",
      },
    ],
  },
  mutations: {
    SET_NEWS_DETAILS: (state, news /*修改缓存新闻详情*/) => {
      let isUpdate = true;
      state.newsDetails.forEach((item, index) => {
        if (item.id == "" && item.content == "") {
          state.newsDetails.splice(index, 1);
        }
        if (item.id == news.id) {
          item = JSON.parse(JSON.stringify(news));
          isUpdate = false;
        }
      });
      if (isUpdate) {
        state.newsDetails.push(news);
      }
    },
    MUTATIONS_CHANGE_AXIOSLOADING: (state, active /*修改全局loading状态*/) => {
      state.axiosLoading = active;
    },
    SET_NEWS_LIST: (state, obj /*修改新闻列表缓存*/) => {
      let isUpdate = true;
      state.newsList.forEach((item) => {
        if (item.type == obj.type && item.page == obj.pageNum) {
          item = JSON.parse(JSON.stringify(obj));
          isUpdate = false;
        }
        if (item && item.list && item.list.length >= 10) {
          item.list = item.list.splice(0, 10);
        }
      });
      if (isUpdate) {
        state.newsList.push(obj);
      }
    },
    MUTATIONS_CHANGE_FOOTER_BAR: (state, active /*修改footerBar文字*/) => {
      state.footerBar.forEach((item) => {
        if (item.key == "3") {
          item.text = active ? "user" : "noLog";
        }
      });
    },
    MUTATIONS_SET_STATE: (state, data /*修改全局state*/) => {
      state[data.key] = data.value;
    },
  },
  actions: {
    ACTION_CHANGE_AXIOSLOADING: ({ commit }, data /*修改全局loading状态*/) => {
      commit("MUTATIONS_CHANGE_AXIOSLOADING", data);
    },
    ACTIONS_CHANGE_FOOTER_BAR: ({ commit }, data /*修改footerBar文字*/) => {
      commit("MUTATIONS_CHANGE_FOOTER_BAR", data);
    },
  },
  modules: {},
  plugins: [createPersistedState()],
});
